<template>
  <div class="dashboard-container">
    <div class="left-column">
      <Tree v-if="!isCollapsed" @deviceSelect="handleDevSelect" style="margin-left: 20px;margin-top: 20px;"></Tree>
    </div>
    <div class="right-column" style="padding:20px">
      <!-- <div style="z-index: 0;" class="scroll_table">
        <div style="display: inline-block;width: 99%">
          <vue-seamless-scroll :data="warnList" class="seamless-warp" style="width: 100%"
            :class-option="optionSingleHeight">
            <ul v-for="item in warnList" :key="item.id" class="table_scroll">
              <li> <el-alert type="warning" effect="dark">
                  <slot name="description">
                    <el-descriptions labelStyle="width:80px" direction="horizontal" :column="4" size="small" border>
                      <el-descriptions-item label="设备Id">{{ item.deviceId }}</el-descriptions-item>
                      <el-descriptions-item label="设备名称">{{ item.deviceName }} </el-descriptions-item>
                      <el-descriptions-item label="报警内容">{{ item.msg }}</el-descriptions-item>
                      <el-descriptions-item label="报警时间">
                        <el-tag size="small">{{ parseTime(item.warnTime) }}</el-tag>
                      </el-descriptions-item>
                    </el-descriptions>
                  </slot>
                </el-alert> </li>
            </ul>
          </vue-seamless-scroll>
        </div>
      </div> -->
      <div id="container" @click="btn"></div>
      <mapxinxi :list="list" :display="isDataReceived" id="mapxinxi"></mapxinxi>
    </div>
  </div>
</template>


<script>
import Tree from "@/components/Tree/Tree";
import { Map, initMap, findMarkerById, moveMapToMarker } from "../utils/map/index";
import EventBus from '../utils/map/click';
import mapxinxi from "../components/mapxinxi/map.vue";
import { Loading } from 'element-ui';
import { listDevice, getDevice, updateWarinfo } from '../api/system/device'
import { listUser } from "../api/system/user"
import { getInfo } from '../api/login'
import { MessageBox } from 'element-ui';
import vueSeamless from 'vue-seamless-scroll'

export default {
  name: "Dashboard",
  components: {
    Tree,
    mapxinxi,
    vueSeamless
  },
  data() {
    return {
      warnList: [],
      isCollapsed: false,
      name: '',
      list: [],
      isDataReceived: false,
      socket: null,
      SocketList: [],
      deptId: null,
      Currentdevice: '',
      statusList: []

    };
  },
  mounted() {
    Loading.service({ text: "地图加载中..." });
    Map().then((data) => {
      Loading.service().close()
    });
    EventBus.$on("marker", (item) => {
      this.Mapxinxi(item.deviceId)
    });
  },
  created() {
    this.name = this.$route.name
    getInfo().then((res) => {
      this.deptId = res.user.deptId
      this.Socket()
    })

  },
  computed: {
    optionSingleHeight() {
      return {
        step: 0.5,//数值越大滚动越快
        limitMoveNum: this.warnList.lenght, // 开始无缝滚动的数据量 this.list
        hoverStop: true,//是否开启鼠标悬停stop
        direction: 1,//0向下1向上2向左3向右
        openWatch: true,//开启数据实时监控刷新dom
        singleHeight: 86,//单步运动挺值得高度(默认值0是无缝不停止的滚动)//竖着
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动)//横着
        waitTime: 1000, // 单步运动停止的时间(默认值1000ms)
      }
    }
  },
  methods: {

    //属性列表选择了设备
    handleDevSelect(e) {
      moveMapToMarker(findMarkerById(e.id.toString()));
    },

    async handleSocketList() {
      for (const item of this.SocketList) {
        if (item.status === '离线') {
          this.Currentdevice = item.deviceId + "--" + item.deptName + "--" + item.deviceName
          await this.open1();
        }
      }
    },
    async handleWarnList() { 
      for (const item of this.warnList) {
        await this.open2(item);
      }
    },
    open2(item) {
      return new Promise((resolve) => {
        const h = this.$createElement;
        this.$notify({
          message: h('p', [
            h('p', { style: 'color: CornflowerBlue' }, '设备编号(ID)：' + item.deviceId),
            h('p', { style: 'color: CornflowerBlue' }, '设备：' + item.deviceName),
            h('p', { style: 'color: CornflowerBlue' }, '时间：' + this.parseTime(item.warnTime)),
            h('p', { style: 'color: Coral' }, '内容：' + item.msg),
          ]),
          type: 'warning',
          offset:150,
          showClose:false,
          onClose: resolve, 
          position: 'bottom-left',
          onClick:function(){
            updateWarinfo({id:item.id,isRead:1}).then(res=>{
              console.log('返回数据',res);
              this.warnList=(this.warnList||[]).filter(s=>s.id!=item.id);
              this.close();
            })
          }
        });
      });
    },
    open1() {
      return new Promise((resolve) => {
        const h = this.$createElement;
        this.$notify.error({
          // title: '提示',
          message: h('i', { style: 'color: teal' }, '设备：' + this.Currentdevice + '已离线'),
          onClose: resolve // 解决 Promise，表示弹框处理完成
        });
      });
    },
    collapseTree() {
      this.isCollapsed = !this.isCollapsed;
    },
    btn() {
      this.isDataReceived = false
    },
    async Mapxinxi(deviceId) {
      this.list = this.SocketList.find(item => item.deviceId == deviceId) ? [this.SocketList.find(item => item.deviceId == deviceId)] : []
      this.isDataReceived = true
    },
    Socket() {
      this.socket = new WebSocket(`${process.env.VUE_APP_WS_URL}/websocket/message?deptId:${this.deptId}`)
      this.socket.onopen = () => {
        console.log('WebSocket 连接已打开');
      };
      this.socket.onmessage = (event) => {
        let eventData = JSON.parse(event.data);
        console.log('数据', eventData);
        if (eventData.type == '0') {
          // 处理收到的消息数据
          this.SocketList = eventData.data;
          // this.statusList = eventData.data;
          console.log('数据---SocketList', this.SocketList);
          this.handleSocketList()
        } else if(eventData.type == '1') {
          this.warnList = eventData.data;
          console.log('数据---warnList', this.warnList);
          this.handleWarnList()
        }else{
          this.statusList = eventData.data;
        }

      };

      this.socket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };

      this.socket.onclose = () => {
        console.log('WebSocket 连接已关闭');
      };
    }
  },

  beforeDestroy() {
    EventBus.$off("marker");
    this.socket.close()
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  display: flex;
}

.left-column {
  flex: 1;
  overflow: hidden;
  transition: flex 0.3s ease-out, minWidth 0.3s ease-out;
  position: relative;
}

.right-column {
  flex: 5.5;
  position: relative; // 添加position: relative属性
}

.arrow-container {
  width: 20px;
  height: 50px;
  background-color: rgba(79, 79, 79, 0.5);
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 1;
}


.arrow {
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-left: 10px solid black;
  cursor: pointer;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

.arrow.collapsed {
  border-left: none;
  border-right: 10px solid black;
}

#container {
  width: 99%;
  height: 85vh;
  z-index: 0;
}

#mapxinxi {
  position: absolute;
  top: 0;
  left: 20px;
  box-shadow: 10px 20px 40px rgba(0, 0, 0, 0.1);
  /* 添加阴影效果 */

}
</style>
